
import React, { PureComponent, Component } from 'react';
import { BasicPagination, isInvalidObject, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
import { Row, Col, Form, Select, Layout, Upload, Button, InputNumber, Table, Input, Alert, Spin, Modal, Drawer, Divider, Icon, Badge, PageHeader, Tabs, Card } from 'antd';

import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout'
import { withRouter } from 'react-router';
// import * as APIService from '../../../axios/api_yq'
import * as APIService from '../../../axios/api_px'
import { baseUrl } from '../../../config'

import { getBase64, } from '../../../utils/action'
import EditTable from '../../../components/EditRowTable';
import DetailsForm from './Components/DetailsForm'
const { confirm } = Modal;

const FormItem = Form.Item;
const { Header, Footer, Sider, Content } = Layout;
const { Option } = Select


class Pygidium extends Component {
    state = {
        type: '尾板调节螺母配合精度记录表',
        dataSource: [],
        dataSource1: [],
        dataSource2: [],
        dataSource3: [],
        dataSource4: [],
        modelData: [],
        modelColumns: [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '机型',
                dataIndex: 'code',
                width: 100,
            },
        ],
        clickSaveFlag: false,
        columns: [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                ellipsis: true,
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '测量点',
                dataIndex: 'measuringPoint',
                sorter: (a, b) => compareString(a.measuringPoint, b.measuringPoint),
                width: 100,
                ellipsis: true,
                editable: true,
                required: true,
            },
            {
                title: '要求标准',
                dataIndex: 'standard',
                sorter: (a, b) => compareString(a.standard, b.standard),
                width: 150,
                ellipsis: true,
                editable: true,
                required: true,
            },
            {
                title: '测量点-调节螺母深度尺寸',
                dataIndex: 'message1',
                sorter: (a, b) => compareString(a.message1, b.message1),
                width: 200,
                ellipsis: true,
            },
            {
                title: '测量点-调节螺母压盖深度尺寸',
                dataIndex: 'message2',
                sorter: (a, b) => compareString(a.message2, b.message2),
                width: 230,
                ellipsis: true,
            },
            {
                title: '实际配合数据',
                dataIndex: 'message3',
                sorter: (a, b) => compareString(a.message3, b.message3),
                width: 150,
                ellipsis: true,
                editable: false,
            },
            {
                title: '操作',
                dataIndex: 'opts',
                render: (text, record) => {
                    const { editingKey, clickSaveFlag } = this.state;
                    const editable = record.id === editingKey;
                    return editable ? (
                        <span>
                            <a
                                disabled={clickSaveFlag}
                                onClick={() => {
                                    this.handleSave(record)
                                }}
                                style={{ marginRight: 8 }}
                            >
                                保存
                            </a>
                            <Divider type='vertical' />
                            <a onClick={() => this.cancel()}>取消</a>
                        </span>
                    ) : (
                        <span>
                            <a disabled={editingKey !== ''} onClick={() => this.edit(record.id)}>
                                编辑
                            </a>
                            <Divider type='vertical' />
                            <a disabled={editingKey !== ''} onClick={() => this.handleDelete(record)}>
                                删除
                            </a>
                        </span>
                    );
                }
            },
        ],
        formData: {},
        loading: true,
        spinning: false,
        editingKey: '',
        visible: false,
        selectedRows: [],
        selectedRowKeys: [],
        isAdd: false,
        newData: {}
    }
    componentDidMount() {
        this.queryProductModel()
        this.queryFormModel()
        this.fetch();
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化数据
    fetch = (pageNum = 1, pageSize = 1000) => {
        this.setState({ loading: true })
        let searchItem = { pageNum, pageSize }
        APIService.queryTailPageList(searchItem).then((item) => {
            if (item.data.code === 200) {
                let dataSource = item.data.data.data, dataSource1 = [], dataSource2 = [], dataSource3 = [], dataSource4 = []
                for (let item of dataSource) {
                    if (item.type == "抽哥林柱检测") {
                        dataSource1.push(item)
                    } else if (item.type == "抽哥林柱正下方检测") {
                        dataSource2.push(item)
                    } else if (item.type == "抽哥林柱对角方向检测") {
                        dataSource3.push(item)
                    } else if (item.type == "抽哥林柱水平方向检测") {
                        dataSource4.push(item)
                    }
                }
                this.setState({
                    loading: false,
                    dataSource, dataSource1, dataSource2, dataSource3, dataSource4,
                    editingKey: ''
                })
                console.log('这是初始化数据', item);
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 适用机型查询
    queryProductModel = () => {
        APIService.queryProductModel({ "pageNum": 1, "pageSize": 1000 }).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            this.setState({ modelData: res.data.data.data })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    // 查询表单基础信息
    queryFormModel = () => {
        APIService.queryFormModel(this.state.type).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            let formData = {}
            if (res.data.data?.data && res.data.data.data.length > 0) {
                formData = res.data.data.data[0]
            }
            this.setState({ formData })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    // 表单信息新增/修改
    alterFormModel = () => {
        const { formData, type } = this.state

        this.DetailForm.validateFields((err, values) => {
            if (err) return
            this.setState({ spinning: true })
            console.log(values, formData, 'formData');
            let data = { ...formData, ...values, formName: type }
            APIService.alterFormModel(data).then(res => {
                if (res.data.code !== 200) {
                    openModalMessage('warning', res.data.msg)
                    return
                }
                openSuccessModal(res.data.msg)
                this.setState({ spinning: false }, this.queryFormModel)
            }).catch(err => {
                openModalMessage('error', err.message)
            })
        })
    }
    // 点击选择按钮
    onChoose = () => {
        const { formData } = this.state
        let model = formData.model ? formData.model : ''
        let selectedRowKeys = model.indexOf('、') != -1 ? model.split('、') : []
        this.setState({ visible: true, selectedRowKeys })
    }
    // 选择适用机型弹窗 - 点击保存
    getModelCode = () => {
        const { selectedRowKeys, selectedRows, formData } = this.state
        let model = selectedRowKeys.join('、')
        formData.model = model
        this.setState({ formData, visible: false })
    }
    //新增/编辑接口
    newOrCompile = (value) => {
        if (value.id == '抽哥林柱检测' || value.id == '抽哥林柱正下方检测' || value.id == '抽哥林柱对角方向检测' || value.id == '抽哥林柱水平方向检测') {
            delete value.id
        }
        console.log(value, 'newOrCompile')
        APIService.alterTailStandard(value).then((item) => {
            this.setState({ clickSaveFlag: false })
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.fetch()
                this.setState({ isAdd: false })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 删除
    handleDelete = (b) => {
        console.log(b, 'b')
        const then = this
        if (b.id == "抽哥林柱检测") {
            const dataSource1 = [...this.state.dataSource1];
            this.setState({ dataSource1: dataSource1.filter(item => item.id !== b.id) });
        } else if (b.id == "抽哥林柱正下方检测") {
            const dataSource2 = [...this.state.dataSource2];
            this.setState({ dataSource2: dataSource2.filter(item => item.id !== b.id) });
        } else if (b.id == "抽哥林柱对角方向检测") {
            const dataSource3 = [...this.state.dataSource3];
            this.setState({ dataSource3: dataSource3.filter(item => item.id !== b.id) });
        } else if (b.id == "抽哥林柱水平方向检测") {
            const dataSource4 = [...this.state.dataSource4];
            this.setState({ dataSource4: dataSource4.filter(item => item.id !== b.id) });
        } else {
            let id = `idList= ${[b.id]}`
            confirm({
                title: '确认删除当项吗，这将影响其他数据模块?',
                onOk() {
                    APIService.deleteTailStandard(id).then((item) => {
                        if (item.data.code === 200) {
                            then.fetch()
                            openSuccessModal('删除成功')
                        } else {
                            openModalMessage('error', item.data.msg)
                        }
                    })
                },
                onCancel() {
                },
            })
        }

    }
    // table上直接修改数据
    loadData = (value, dataSource) => {
        console.log('在表格修改数据后保存的数据:', value, dataSource);
        this.newOrCompile(value)
    }
    // 点击编辑按钮
    edit = (id) => { this.setState({ editingKey: id }); }
    // 点击取消按钮
    cancel = () => {
        const { newData, isAdd } = this.state
        if (isAdd) {
            this.handleDelete(newData)
        }
        this.setState({ editingKey: '', clickSaveFlag: false });
    };

    // 新增行
    handleAdd = (type) => {
        // 抽哥林柱检测
        if (type == 1) {
            const { dataSource1 } = this.state;

            const newData = {
                id: '抽哥林柱检测',
                type: '抽哥林柱检测',
                measuringPoint: ``,
                message1: '',
                standard: '',
                message3: '',
                message2: '',
            };
            this.setState({
                dataSource1: [newData, ...dataSource1],
                editingKey: '抽哥林柱检测',
                newData,
                isAdd: true
            });
        }
        // 抽哥林柱正下方检测
        else if (type == 2) {
            const { dataSource2 } = this.state;

            const newData = {
                id: '抽哥林柱正下方检测',
                type: '抽哥林柱正下方检测',
                measuringPoint: ``,
                message1: '',
                standard: '',
                message3: '',
                message2: '',
            };
            this.setState({
                dataSource2: [newData, ...dataSource2],
                editingKey: '抽哥林柱正下方检测',
                newData,
                isAdd: true
            });
        }
        // 抽哥林柱对角方向检测
        else if (type == 3) {
            const { dataSource3 } = this.state;

            const newData = {
                id: '抽哥林柱对角方向检测',
                type: '抽哥林柱对角方向检测',
                measuringPoint: ``,
                message1: '',
                standard: '',
                message3: '',
                message2: '',
            };
            this.setState({
                dataSource3: [newData, ...dataSource3],
                editingKey: '抽哥林柱对角方向检测',
                newData,
                isAdd: true
            });
        }
        // 抽哥林柱水平方向检测
        else if (type == 4) {
            const { dataSource4 } = this.state;

            const newData = {
                id: '抽哥林柱水平方向检测',
                type: '抽哥林柱水平方向检测',
                measuringPoint: ``,
                message1: '',
                standard: '',
                message3: '',
                message2: '',
            };
            this.setState({
                dataSource4: [newData, ...dataSource4],
                editingKey: '抽哥林柱水平方向检测',
                newData,
                isAdd: true
            });
        }
    };
    // 保存
    handleSave = (row) => {
        console.log(row, 'row')
        this.setState({ clickSaveFlag: true })
        if (row.type == '抽哥林柱检测') {
            this.editTable1.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        } else if (row.type == '抽哥林柱正下方检测') {
            this.editTable2.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        } else if (row.type == '抽哥林柱对角方向检测') {
            this.editTable3.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        } else if (row.type == '抽哥林柱水平方向检测') {
            this.editTable4.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        }
    };
    // 选择某一行数据
    chooseRow = record => {
        let flag = true;
        let index = 0;
        this.state.selectedRowKeys.forEach((row, i) => {
            if (row === record.code) {
                flag = false;
                index = i;
            }
        })
        const selectedRowKeys = this.state.selectedRowKeys;
        const selectedRows = this.state.selectedRows;
        if (flag) {
            selectedRowKeys.push(record.code);
            selectedRows.push(record);
        } else {
            selectedRowKeys.splice(index, 1);
            selectedRows.splice(index, 1);
        }
        this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
    };

    // 打开详情页
    openDetails = () => {
        const { dataSource1, dataSource2, dataSource3, dataSource4, formData, type } = this.state
        let data = { title: type + '-表单样式', queryForm: { dataSource1, dataSource2, dataSource3, dataSource4, formData }, path: 'Pygidium' }
        localStorage.setItem('Pygidium_Report', JSON.stringify(data))
        this.props.history.push({ pathname: "/Pygidium_Report", data })
    }

    render() {
        const { form: { getFieldDecorator } } = this.props;
        const { isAdd, loading, type, spinning, formData, editingKey, modelColumns, modelData, selectedRowKeys, visible, columns, dataSource1, dataSource2, dataSource3, dataSource4 } = this.state

        const titleStyle = { fontWeight: 'bold', fontSize: 14 }

        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys,
                })
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                const keys = [... this.state.selectedRowKeys];
                const rows = [... this.state.selectedRows];
                if (selected) {
                    changeRows.forEach(row => {
                        if (isInvalidObject(keys.find(key => key === row.model))) {
                            keys.push(row.model);
                            rows.push(row);
                        }
                    })
                } else {
                    changeRows.forEach(row => {
                        keys.splice(keys.indexOf(row.model), 1);
                        rows.splice(rows.indexOf(row), 1);
                    })
                }
                this.setState({ selectedRows: rows, selectedRowKeys: keys })
            }
        }
        return (
            <Spin spinning={spinning}>
                <BasicLayoutSearch>
                    <PageHeader
                        style={{ padding: '4px 24px' }}
                        title={type}>
                    </PageHeader>
                </BasicLayoutSearch>
                <Layout className="layout-model">
                    <DetailsForm
                        ref={node => this.DetailForm = node}
                        formData={formData}
                        onAlterFormModel={this.alterFormModel}
                        onChoose={this.onChoose}
                        titleStyle={titleStyle}
                        message="说明：这是一个定制化界面，只允许修改部分数据，如需样式变更，请联系开发人员！页面样式参考《附录二 尾板调节螺母压盖与调节螺母配合精度记录表》。"
                        openDetails={this.openDetails}
                    />
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>1、抽哥林柱检测</div>}
                        extra={<Button onClick={() => this.handleAdd(1)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource1}
                                    columns={columns}
                                    ref={node => (this.editTable1 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>2、抽哥林柱正下方检测</div>}
                        extra={<Button onClick={() => this.handleAdd(2)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource2}
                                    columns={columns}
                                    ref={node => (this.editTable2 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>3、抽哥林柱对角方向检测</div>}
                        extra={<Button onClick={() => this.handleAdd(3)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource3}
                                    columns={columns}
                                    ref={node => (this.editTable3 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>4、抽哥林柱水平方向检测</div>}
                        extra={<Button onClick={() => this.handleAdd(4)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource4}
                                    columns={columns}
                                    ref={node => (this.editTable4 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>

                {/* 选择适用机型 */}
                <Modal
                    title={'选择适用机型'}
                    visible={visible}
                    okText={'提交'}
                    cancelText={'取消'}
                    onOk={this.getModelCode}
                    onCancel={() => this.setState({ visible: false })}
                >
                    <TableCustomize
                        columns={modelColumns}
                        rowKey={(record) => record.code}
                        dataSource={modelData}
                        pagination={false}
                        allowDrafting={true}
                        rowSelection={rowSelection}
                        onRow={(record, rowKey) => ({
                            onClick: this.chooseRow.bind(this, record, rowKey)
                        })}
                    />
                </Modal>
            </Spin>
        )
    }
}

export default Form.create()(withRouter(Pygidium));